import React, { useState, useEffect } from "react";
import {
  Card,
  List,
  Space,
  Button,
  Tag,
  Modal,
  message,
  Typography,
  Avatar,
  Tooltip,
  Empty,
  Spin,
  Form,
  Input,
  Select,
  Popconfirm,
  Alert,
  Divider,
} from "antd";
import {
  MessageOutlined,
  LikeOutlined,
  LikeFilled,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  PushpinOutlined,
  SendOutlined,
  EditOutlined,
  DeleteOutlined,
  CommentOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionReply,
} from "../../../common/types/discussion";
import { useUser } from "../../../../contexts/UserContext";
import { AIService } from "../../../../services/ai";

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  if (role === "teacher") {
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

const StyledCard = styled(Card)`
  margin-bottom: 16px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const DiscussionItem = styled.div`
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
  
  &:last-child {
    border-bottom: none;
  }
`;

const AIResponseCard = styled(Card)`
  margin-top: 16px;
  border-left: 4px solid #1890ff;
  background: #f0f8ff;
`;

const MyDiscussions: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [myDiscussions, setMyDiscussions] = useState<DiscussionPost[]>([]);
  const [selectedDiscussion, setSelectedDiscussion] = useState<string>();
  const [expandedReplies, setExpandedReplies] = useState<Set<string>>(new Set());
  const [likedDiscussions, setLikedDiscussions] = useState<Set<string>>(new Set());
  
  // 编辑相关状态
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingDiscussion, setEditingDiscussion] = useState<DiscussionPost | null>(null);
  const [editForm] = Form.useForm();
  
  // AI回复相关状态
  const [aiLoading, setAiLoading] = useState<string | null>(null);
  
  // 回复表单
  const [replyForm] = Form.useForm();
  const [aiService] = useState(new AIService());

  useEffect(() => {
    loadMyDiscussions();
  }, []);

  const loadMyDiscussions = async () => {
    setLoading(true);
    try {
      // 生成我的讨论数据，与主讨论区保持一致
      const generateMyDiscussions = (): DiscussionPost[] => {
        const topics = [
          "关于算法复杂度的理解",
          "数据库设计经验分享", 
          "计算机网络实验心得",
          "前端框架学习心得",
          "机器学习入门问题"
        ];

        const contents = [
          "在学习算法时，对时间复杂度和空间复杂度的概念还不是很清楚，希望有经验的同学能分享一下学习心得。",
          "最近在做数据库课程设计，想和大家分享一下设计过程中的经验和遇到的问题。",
          "完成了计算机网络课程的实验，对TCP/IP协议有了更深的理解，想和大家交流一下学习心得。",
          "在学习React和Vue时遇到了一些困惑，想请教一下大家的学习方法和经验。",
          "刚开始学习机器学习，对监督学习和无监督学习的区别还不是很清楚，希望能得到一些指导。"
        ];

        const tags = [
          ["算法", "复杂度", "学习心得"],
          ["数据库", "课程设计", "经验分享"],
          ["计算机网络", "实验", "TCP/IP"],
          ["前端开发", "React", "Vue"],
          ["机器学习", "监督学习", "入门"]
        ];

        return Array.from({ length: 5 }, (_, index) => {
          const hasAIResponse = index % 2 === 0; // 每2个讨论中有1个有AI回复
          const replyCount = Math.floor(Math.random() * 5) + 1; // 1-5条回复
          
          // 生成回复
          const replies: DiscussionReply[] = Array.from({ length: replyCount }, (_, replyIndex) => ({
            id: `${index}-${replyIndex}`,
            content: [
              "这个问题很有意思，我也遇到过类似的情况。",
              "感谢分享，这个思路很有启发性。",
              "我觉得可以从另一个角度来思考这个问题。",
              "这个解决方案确实很实用，学到了！",
              "有没有更详细的参考资料推荐？"
            ][replyIndex % 5],
            author: {
              id: `user-${replyIndex}`,
              name: ["张老师", "李同学", "王助教", "赵同学", "陈老师"][replyIndex % 5],
              role: replyIndex % 2 === 0 ? "teacher" as const : "student" as const,
              avatar: getDefaultAvatar(["张老师", "李同学", "王助教", "赵同学", "陈老师"][replyIndex % 5], replyIndex % 2 === 0 ? "teacher" : "student")
            },
            createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
            likes: Math.floor(Math.random() * 10)
          }));

          return {
            id: `my-discussion-${index + 1}`,
            title: topics[index],
            content: contents[index],
            author: {
              id: String(user?.id || "current_user"),
              name: user?.name || "当前用户",
              role: "student" as const,
              avatar: getDefaultAvatar(user?.name || "当前用户", "student")
            },
            createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
            tags: tags[index],
            views: Math.floor(Math.random() * 500) + 50,
            likes: Math.floor(Math.random() * 30) + 5,
            replies,
            aiResponse: hasAIResponse ? {
              content: `关于"${topics[index]}"，我来为您详细解答：

${contents[index]}

基于您的问题，我建议从以下几个方面来思考：

1. **深入理解**：掌握相关概念的核心要点
2. **实践应用**：在实际项目中验证理论
3. **持续学习**：关注技术发展趋势
4. **交流分享**：与同行交流学习心得

希望这个回答对您有帮助！`,
              createTime: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
              status: "completed" as const
            } : undefined,
            aiRequestStatus: hasAIResponse ? "completed" as const : "pending" as const
          };
        });
      };

      const mockMyDiscussions = generateMyDiscussions();
      setMyDiscussions(mockMyDiscussions);
    } catch (error) {
      console.error("加载我的讨论失败:", error);
      message.error("加载我的讨论失败");
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (discussion: DiscussionPost) => {
    setEditingDiscussion(discussion);
    editForm.setFieldsValue({
      title: discussion.title,
      content: discussion.content,
      tags: discussion.tags
    });
    setEditModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      
      setMyDiscussions(prev => prev.map(d => 
        d.id === editingDiscussion?.id 
          ? { ...d, ...values }
          : d
      ));

      setEditModalVisible(false);
      setEditingDiscussion(null);
      editForm.resetFields();
      message.success("讨论更新成功！");
    } catch (error) {
      console.error("更新讨论失败:", error);
      message.error("更新失败，请重试");
    }
  };

  const handleDelete = async (discussionId: string) => {
    try {
      setMyDiscussions(prev => prev.filter(d => d.id !== discussionId));
      message.success("讨论删除成功！");
    } catch (error) {
      console.error("删除讨论失败:", error);
      message.error("删除失败，请重试");
    }
  };

  const handleLike = async (discussionId: string) => {
    try {
      const isLiked = likedDiscussions.has(discussionId);
      const newLikedDiscussions = new Set(likedDiscussions);
      
      if (isLiked) {
        newLikedDiscussions.delete(discussionId);
      } else {
        newLikedDiscussions.add(discussionId);
      }
      
      setLikedDiscussions(newLikedDiscussions);
      
      setMyDiscussions(prev => prev.map(d => 
        d.id === discussionId 
          ? { ...d, likes: isLiked ? d.likes - 1 : d.likes + 1 }
          : d
      ));

      message.success(isLiked ? "取消点赞" : "点赞成功");
    } catch (error) {
      console.error("点赞失败:", error);
      message.error("操作失败，请重试");
    }
  };

  const handleViewReplies = (discussionId: string) => {
    const newExpandedReplies = new Set(expandedReplies);
    if (newExpandedReplies.has(discussionId)) {
      newExpandedReplies.delete(discussionId);
    } else {
      newExpandedReplies.add(discussionId);
    }
    setExpandedReplies(newExpandedReplies);
  };

  const handleReply = async (discussionId: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      const values = await replyForm.validateFields();
      const newReply: DiscussionReply = {
        id: Date.now().toString(),
        content: values.content,
        author: {
          id: String(user.id),
          name: user.name,
          role: user.role,
          avatar: getDefaultAvatar(user.name, user.role)
        },
        createTime: new Date().toLocaleString('zh-CN'),
        likes: 0
      };

      setMyDiscussions(prev => prev.map(d => 
        d.id === discussionId 
          ? { ...d, replies: [...d.replies, newReply] }
          : d
      ));

      replyForm.resetFields();
      message.success("回复成功！");
    } catch (error) {
      if (error instanceof Error) {
        message.error("回复失败，请重试");
        console.error("回复失败:", error);
      }
    }
  };

  const handleRequestAIResponse = async (discussionId: string) => {
    try {
      setAiLoading(discussionId);
      message.loading("正在申请AI回复...", 2);
      
      // 模拟AI回复生成
      setTimeout(() => {
        const discussion = myDiscussions.find(d => d.id === discussionId);
        if (discussion) {
          const aiResponse = {
            content: `关于"${discussion.title}"，AI为您提供以下专业解答：

${discussion.content}

基于您的问题，我建议：

1. **深入理解**：掌握相关概念的核心要点
2. **实践应用**：在实际项目中验证理论
3. **持续学习**：关注技术发展趋势
4. **交流分享**：与同行交流学习心得

希望这个回答对您有帮助！`,
            createTime: new Date().toLocaleString('zh-CN'),
            status: "completed" as const
          };

          setMyDiscussions(prev => prev.map(d => 
            d.id === discussionId 
              ? { ...d, aiResponse, aiRequestStatus: "completed" as const }
              : d
          ));

          message.success("AI回复已生成！");
        }
      }, 3000);
    } catch (error) {
      console.error("申请AI回复失败:", error);
      message.error("申请失败，请重试");
    } finally {
      setAiLoading(null);
    }
  };

  const renderDiscussionItem = (discussion: DiscussionPost) => (
    <DiscussionItem key={discussion.id}>
      <div style={{ width: "100%" }}>
        {/* 讨论头部信息 */}
        <div style={{ display: "flex", alignItems: "flex-start", marginBottom: "16px" }}>
          <Avatar 
            src={discussion.author.avatar}
            icon={<UserOutlined />} 
            style={{ marginRight: "12px", marginTop: "4px" }}
          />
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
              <Space>
                {discussion.isPinned && (
                  <Tooltip title="已置顶">
                    <PushpinOutlined style={{ color: "#1890ff" }} />
                  </Tooltip>
                )}
                <Text
                  style={{ 
                    fontSize: "16px", 
                    fontWeight: 600, 
                    color: "#1890ff",
                    cursor: "pointer"
                  }}
                >
                  {discussion.title}
                </Text>
                {discussion.aiResponse && (
                  <Tag icon={<RobotOutlined />} color="purple">
                    AI已回复
                  </Tag>
                )}
              </Space>
            </div>
            <div style={{ display: "flex", alignItems: "center", marginBottom: "12px" }}>
              <Space>
                <Text strong>{discussion.author.name}</Text>
                <Tag
                  color={
                    discussion.author.role === "teacher" ? "blue" : "default"
                  }
                >
                  {discussion.author.role === "teacher" ? "教师" : "学生"}
                </Tag>
                <Text type="secondary">发布于 {discussion.createTime}</Text>
              </Space>
            </div>
            <div style={{ marginBottom: "12px" }}>
              {discussion.tags.map((tag) => (
                <Tag
                  key={tag}
                  color="default"
                  style={{ cursor: "pointer", marginRight: "8px" }}
                >
                  {tag}
                </Tag>
              ))}
            </div>
          </div>
        </div>

        {/* 讨论内容 */}
        <div style={{ marginBottom: "16px", paddingLeft: "44px" }}>
          <Paragraph
            ellipsis={{ rows: 2, expandable: true, symbol: "展开" }}
            style={{ margin: 0, fontSize: "14px", lineHeight: "1.6" }}
          >
            {discussion.content}
          </Paragraph>
        </div>

        {/* 操作按钮区域 */}
        <div style={{ 
          display: "flex", 
          justifyContent: "space-between", 
          alignItems: "center",
          paddingLeft: "44px",
          paddingTop: "12px",
          borderTop: "1px solid #f5f5f5"
        }}>
          <Space size="large">
            <Tooltip title="点击增加浏览量">
              <Button
                type="text"
                icon={<EyeOutlined />}
                style={{ color: "#666" }}
              >
                {discussion.views}
              </Button>
            </Tooltip>
            <Tooltip title={
              user 
                ? (likedDiscussions.has(discussion.id) ? "取消点赞" : "点赞")
                : "登录后即可点赞"
            }>
              <Button
                type="text"
                icon={likedDiscussions.has(discussion.id) ? <LikeFilled /> : <LikeOutlined />}
                onClick={() => handleLike(discussion.id)}
                disabled={!user}
                style={{ 
                  color: likedDiscussions.has(discussion.id) ? "#ff4d4f" : "#666"
                }}
              >
                {discussion.likes}
              </Button>
            </Tooltip>
            <Tooltip title="查看回复">
              <Button
                type="text"
                icon={<MessageOutlined />}
                onClick={() => handleViewReplies(discussion.id)}
                style={{ color: "#666" }}
              >
                {discussion.replies.length}
              </Button>
            </Tooltip>
            {discussion.aiRequestStatus === "pending" && (
              <Tooltip title="申请AI回复">
                <Button
                  type="text"
                  icon={<CommentOutlined />}
                  onClick={() => handleRequestAIResponse(discussion.id)}
                  loading={aiLoading === discussion.id}
                  style={{ color: "#666" }}
                >
                  申请AI
                </Button>
              </Tooltip>
            )}
          </Space>
          
          {/* 管理按钮 */}
          <Space>
            <Tooltip title="编辑讨论">
              <Button
                type="text"
                icon={<EditOutlined />}
                onClick={() => handleEdit(discussion)}
                style={{ color: "#666" }}
              >
                编辑
              </Button>
            </Tooltip>
            <Popconfirm
              title="确定要删除这个讨论吗？"
              description="删除后无法恢复，请谨慎操作。"
              onConfirm={() => handleDelete(discussion.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="删除讨论">
                <Button
                  type="text"
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Tooltip>
            </Popconfirm>
          </Space>
        </div>

        {/* AI回复显示 */}
        {discussion.aiResponse && (
          <div style={{ 
            marginTop: "16px", 
            paddingLeft: "44px",
            padding: "16px",
            backgroundColor: "#f0f8ff",
            borderRadius: "8px",
            border: "1px solid #d6e4ff"
          }}>
            <div style={{ display: "flex", alignItems: "center", marginBottom: "12px" }}>
              <RobotOutlined style={{ color: "#1890ff", marginRight: "8px" }} />
              <Text strong style={{ color: "#1890ff" }}>AI回复</Text>
              <Text type="secondary" style={{ marginLeft: "8px", fontSize: "12px" }}>
                {discussion.aiResponse.createTime}
              </Text>
            </div>
            <Paragraph style={{ margin: 0, fontSize: "14px", lineHeight: "1.6" }}>
              {discussion.aiResponse.content}
            </Paragraph>
          </div>
        )}

        {/* 回复列表 */}
        {expandedReplies.has(discussion.id) && (
          <div style={{ 
            marginTop: "16px", 
            paddingLeft: "44px"
          }}>
            <div style={{ 
              padding: "16px",
              backgroundColor: "#fafafa",
              borderRadius: "8px"
            }}>
              <div style={{ marginBottom: "16px" }}>
                <Text strong>回复 ({discussion.replies.length})</Text>
              </div>
              
              {discussion.replies.length > 0 ? (
                <List
                  dataSource={discussion.replies}
                  renderItem={(reply) => (
                    <div style={{ 
                      padding: "12px 0",
                      borderBottom: "1px solid #f0f0f0"
                    }}>
                      <div style={{ display: "flex", alignItems: "flex-start" }}>
                        <Avatar 
                          src={reply.author.avatar}
                          icon={<UserOutlined />} 
                          size="small"
                          style={{ marginRight: "8px", marginTop: "2px" }}
                        />
                        <div style={{ flex: 1 }}>
                          <div style={{ display: "flex", alignItems: "center", marginBottom: "4px" }}>
                            <Text strong style={{ fontSize: "13px" }}>
                              {reply.author.name}
                            </Text>
                            <Tag
                              color={reply.author.role === "teacher" ? "blue" : "default"}
                              style={{ marginLeft: "8px", fontSize: "12px" }}
                            >
                              {reply.author.role === "teacher" ? "教师" : "学生"}
                            </Tag>
                            <Text type="secondary" style={{ marginLeft: "8px", fontSize: "12px" }}>
                              {reply.createTime}
                            </Text>
                          </div>
                          <Paragraph style={{ margin: 0, fontSize: "13px", lineHeight: "1.5" }}>
                            {reply.content}
                          </Paragraph>
                        </div>
                      </div>
                    </div>
                  )}
                />
              ) : (
                <div style={{ textAlign: "center", padding: "20px", color: "#999" }}>
                  暂无回复
                </div>
              )}
            </div>
          </div>
        )}

        {/* 回复表单 */}
        {user && (
          <div style={{ 
            marginTop: "16px", 
            paddingLeft: "44px",
            padding: "16px",
            backgroundColor: "#fafafa",
            borderRadius: "8px"
          }}>
            <Form form={replyForm}>
              <Form.Item
                name="content"
                rules={[{ required: true, message: "请输入回复内容" }]}
                style={{ marginBottom: "24px" }}
              >
                <TextArea
                  placeholder="写下你的回复..."
                  autoSize={{ minRows: 2, maxRows: 6 }}
                  maxLength={500}
                  showCount
                  style={{ borderRadius: "6px" }}
                />
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }}>
                <div style={{ 
                  display: "flex", 
                  justifyContent: "space-between", 
                  alignItems: "center" 
                }}>
                  <div style={{ flex: 1 }}></div>
                  <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={() => handleReply(discussion.id)}
                    style={{ borderRadius: "6px" }}
                  >
                    发表回复
                  </Button>
                </div>
              </Form.Item>
            </Form>
          </div>
        )}
      </div>
    </DiscussionItem>
  );

  return (
    <div style={{ padding: "24px" }}>
      <div style={{ marginBottom: 24 }}>
        <Title level={3}>我的讨论</Title>
        <Alert
          message="AI回复功能说明"
          description="您可以为自己发布的讨论申请AI回复。AI会根据您的问题内容提供专业的解答和建议。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
      </div>

      {loading ? (
        <div style={{ textAlign: "center", padding: "50px" }}>
          <Spin size="large" />
        </div>
      ) : myDiscussions.length === 0 ? (
        <Empty 
          description="您还没有发布过讨论" 
          style={{ marginTop: 50 }}
        />
      ) : (
        <List
          dataSource={myDiscussions}
          renderItem={renderDiscussionItem}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      )}

      {/* 编辑讨论模态框 */}
      <Modal
        title="编辑讨论"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setEditingDiscussion(null);
          editForm.resetFields();
        }}
        onOk={handleEditSubmit}
        okText="保存"
        cancelText="取消"
        destroyOnClose
      >
        <Form form={editForm} layout="vertical">
          <Form.Item
            name="title"
            label="标题"
            rules={[
              { required: true, message: "请输入标题" },
              { max: 100, message: "标题最多100个字符" },
            ]}
          >
            <Input placeholder="请输入讨论标题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="内容"
            rules={[
              { required: true, message: "请输入内容" },
              { max: 2000, message: "内容最多2000个字符" },
            ]}
          >
            <TextArea
              placeholder="请详细描述你的问题或想法..."
              autoSize={{ minRows: 4, maxRows: 8 }}
              showCount
              maxLength={2000}
            />
          </Form.Item>

          <Form.Item
            name="tags"
            label="标签"
            rules={[
              { required: true, message: "请至少选择一个标签" },
              { type: "array", max: 3, message: "最多选择3个标签" },
            ]}
          >
            <Select
              mode="multiple"
              placeholder="选择或输入标签"
              options={[
                "算法", "复杂度", "学习心得", "数据库", "课程设计", "经验分享",
                "计算机网络", "实验", "TCP/IP", "前端开发", "React", "Vue",
                "机器学习", "监督学习", "入门"
              ].map((tag) => ({ label: tag, value: tag }))}
              allowClear
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MyDiscussions; 